package cn.kgc.javaweb.servlet;

import cn.kgc.javaweb.entity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 * @author: mosin
 * @version: v1.0  2022/9/1
 * 查询用户信息列表 以表格的形式响应给前端页面
 */
public class UserListServlet extends HttpServlet {


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // TODO 查询数据库 获取用户信息列表

        ArrayList<User> users = new ArrayList<>();
        for (int i = 0; i <5 ; i++) {
            User user = new User();
            user.setId(i);
            user.setPassword("1234"+i);
            user.setUsername("admin"+i);
            user.setAge(20+i);
            String sex  = i%2==0?"男":"女";
            user.setSex(sex);
            users.add(user);
        }

        // 响应数据到前端页面
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        //写出表格以及表格中的数据

        writer.write("<table border='1' cellspacing='0' width='100%' height='300px' >");
        // 遍历集合
        for (User user : users) {
            writer.write("<tr>");
            writer.write("<td>"+user.getId()+"</td>");
            writer.write("<td>"+user.getUsername()+"</td>");
            writer.write("<td>"+user.getPassword()+"</td>");
            writer.write("<td>"+user.getAge()+"</td>");
            writer.write("<td>"+user.getSex()+"</td>");
            writer.write("</tr>");
        }

        writer.write("</table>");
        // 释放资源
        writer.close();
    }
}
